package com.ruoyi.app.framework.interceptor;

import com.alibaba.fastjson.JSON;
import com.ruoyi.app.common.utils.JwtUtil;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.entity.VO.business.SysUserVO;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class BusinessAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object object) {
        //如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有PassToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            if (method.getAnnotation(PassToken.class).required()) {
                return true;
            }
        }
        //从请求头中取出token
        String token = request.getHeader("token");
        if (token == null) {
            throw new UnauthorizedException("请重新登录！");
        }
        SysUserVO user = JSON.parseObject(JwtUtil.getBusiness(token), SysUserVO.class);
        if (user == null) {
            throw new UnauthorizedException("请重新登录！");
        }
        String signJson = "{\"salt\":\"" + user.getSalt() + "\",\"userId\":" + user.getUserId() + ",\"shopId\":" + user.getShopId() + "}";
        if (!JwtUtil.businessVerify(token, signJson, user.getSalt())) {
            throw new UnauthorizedException("请重新登录！");
        }
        request.setAttribute("userId", user.getUserId());
        request.setAttribute("shopId", user.getShopId());
        return true;
    }

}